package com.web.controller;

import com.domain.Employee;
import com.service.EmployeeService;
import com.service.PermissionService;
import com.util.JsonResult;
import com.util.UserContext;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author shkstart
 * @create 2022/3/14-17:22
 */
@Controller
public class LoginController {

    @RequestMapping("/login")
    @ResponseBody
    public JsonResult login(String username,String password){
        try {
            // 1、获取subject主体
            Subject subject = SecurityUtils.getSubject();
            // 2、将前端传过来的参数封装为令牌
            //方式一：登录时，按照指定的方式对密码加密然后再和数据库中的加密过的密码进行匹配
            /*Md5Hash md5Hash = new Md5Hash(password, username);
            UsernamePasswordToken token = new UsernamePasswordToken(username, md5Hash.toString());*/
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            // 3、使用 shiro 提供的api来登录
            subject.login(token);
            return new JsonResult();
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            return new JsonResult(false,"用户名不存在");
        }catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            return new JsonResult(false,"密码错误");
        }catch (DisabledAccountException e) {
            e.printStackTrace();
            return new JsonResult(false,e.getMessage());
        }
    }

    /*
    @Autowired
    private EmployeeService service;
    @Autowired
    private PermissionService permissionService;

    @RequestMapping("/login")
    @ResponseBody
    public JsonResult login(String username,String password, HttpSession session){
            Employee employee = service.login(username, password);
            //把员工放到session中
            //session.setAttribute(UserContext.EMP_IN_SESSION,employee);
            UserContext.setCurrentUser(employee);

            //判断是否是超级管理员，如果不是就查询权限表达式列表，存到session中
            if(! employee.isAdmin()){
                //根据登录用户id查询员工拥有的权限表达式列表，存到session中
                List<String> expressions = permissionService.selectByEmpId(employee.getId());
                //session.setAttribute(UserContext.USER_EXPRESSIONS_IN_SESSION,expressions);
                UserContext.setExpression(expressions);
            }
            return new JsonResult();
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){
        //销毁会话
        session.invalidate();
        return "redirect:/login.html";
    }*/
}
